var map;
var fmapLayerIndex = "";
var orgMapInfo = null;
var mapLevel = null; //地图等级全局变量
var firstLayer = null;

//联网单位初始化室内地图
//0：平台 1：单位 2：建筑物 3：九小场所
var int_MainFmap = function (
  organizationId,
  type,
  el,
  nine,
  callback,
  indoorId
) {
  if (nineCode > 0) {
    indoorId = indoorId || this.indoorId;
  }
  common.loading(1);
  //显示
  Dao.getIndoorInfo(
    {
      bizId: organizationId,
      type: type ? type * 1 : 1,
    },
    function (data) {
      if (data != null) {
        createMap(data, el, nine, null, indoorId);
      } else {
        if (callback) {
          callback();
        } else {
          if (el) {
            jQuery("#" + el).hide();
          }
        }
      }
      common.loading(0);
    }
  );
};

//生成地图
var curIndoor = "";
var createMap = function (options, el, nine, oneMarkData, indoorId) {
  loadFengmap()
    .then(() => {
      let coords = oneMarkData
        ? {
            x: JSON.parse(oneMarkData.mapLocation)[0].x,
            y: JSON.parse(oneMarkData.mapLocation)[0].y,
            groupID: JSON.parse(oneMarkData.mapLocation)[0].indoorId * 1,
          }
        : "";
      if (nineCode > 0) {
        curIndoor = indoorId ? indoorId * 1 : "";
      } else {
        curIndoor = indoorId;
      }
      // 初始化
      // 定义全局map变量
      map = new fengmap.FMMap({
        // 渲染dom
        container: el
          ? document.getElementById(el)
          : document.getElementById("mapContent"),
        //地图数据位置
        mapServerURL: REMOTESTATICPATH + "fmap/data/" + options.fmapId,
        //主题数据位置
        mapThemeURL: REMOTESTATICPATH + options.topicUrl,
        //设置主题
        defaultThemeName: options.topicName,
        //支持单击模型高亮，false为单击时模型不高亮
        modelSelectedEffect: true,
        //必要，地图应用名称，通过蜂鸟云后台创建
        appName: options.appName,
        //必要，地图应用密钥，通过蜂鸟云后台获取
        key: options.appKey,
        //楼层间隔
        defaultGroupSpace: 10,
        //初始化地图等级大小
        defaultMapScaleLevel: options.scaleLevel || 18,
        //初始化聚焦层数
        // defaultFocusGroup: 3,
        //除了聚焦层数其它楼层是否虚化
        focusAlphaMode: false,
        compassOffset: [28, 20], // 设置初始指南针的偏移量，默认为[28, 20],左：28px,上：20px。
        compassSize: 80,
        // //瓦片加载
        // tile:true
      });

      // 打开Fengmap服务器的地图数据和主题
      map.openMapById(options.fmapId);
      // 地图加载完回调事件
      map.on("loadComplete", function () {
        // map.themeName='967110';
        //map.viewMode = fengmap.FMViewMode.MODE_2D;

        if (curIndoor === "" || curIndoor === undefined || curIndoor === null) {
          // 设置所有楼层可见
          map.visibleGroupIDs = map.groupIDs;
        } else {
          // 隐藏所有楼层，指定显示楼层
          for (var i in map.groupIDs) {
            map.getFMGroup(map.groupIDs[i]).show = false;
            if (map.groupIDs[i] == curIndoor) {
              map.getFMGroup(map.groupIDs[i]).show = true;
              map.focusGroupID = map.groupIDs[i]; //设置聚焦楼层
            }
          }
        }

        // 设置透明
        map.setBackgroundColor("#ffffff", 0);
        if (options.maxTilt) {
          try {
            let maxTilt = JSON.parse(options.maxTilt);
            map.tiltAngle = maxTilt.tiltAngle * 1;
            map.rotateAngle = maxTilt.rotateAngle * 1;
            map.focusGroupID = maxTilt.groupID * 1;
            map.groupSpace = maxTilt.groupSpace * 1;
            //中心点
            let pnt = {
              x: maxTilt.x * 1,
              y: maxTilt.y * 1,
              groupID: maxTilt.groupID * 1,
            };
            //跳转
            map.moveTo(pnt);
          } catch (error) {}
        }
        //地图手势对象
        var controller = map.gestureEnableController;
        controller.enableMapPan = true; // 可移动
        controller.enableMapRotate = true; // 可旋转
        controller.enableMapIncline = true; //可倾斜
        controller.enableMapPinch = true; //可缩放
        controller.enableMapSingleTap = false; //不可单击
        coords ? map.moveTo(coords) : "";
        if (map.fmapID == "njtlzhxf") {
          map.mapScale = 400;
        }
        if (nine == 1) {
          getFacsMarkByNineSmall();
        } else {
          if (oneMarkData) {
            addOneMarker(oneMarkData);
          }
        }
      });
    })
    .catch((err) => {
      console.error("地图加载失败");
    });
};

function getFacsMarkByNineSmall() {
  if (nineCode) {
    Dao.getFacsMarkByNineSmall_ajax(
      {
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
        nineSmallId: nineCode,
      },
      function (data) {
        if (data && data.length > 0) {
          dealMarkerData(data);
        }
      },
      false
    );
  }
}

//处理标注点信息
var dealMarkerData = function (markData) {
  if (firstLayer) {
    firstLayer.removeAll();
    firstLayer = null;
  }
  var coords = [];
  Dao.getDict(
    {
      userName: userInfor.accountName,
      deviceId: appKeyObj.deviceId,
      code: 57,
    },
    function (re) {
      var dataBy57 = re;
      var result = markData;
      for (var i in result) {
        for (var a in dataBy57.dictValueObj) {
          var dictValue57 = JSON.parse(dataBy57.dictValueObj[a].dictValue);
          for (var b in dictValue57) {
            if (dictValue57[b].id == result[i].type) {
              var coord = {
                x: JSON.parse(result[i].mapLocation)[0].x,
                y: JSON.parse(result[i].mapLocation)[0].y,
                z: JSON.parse(result[i].mapLocation)[0].z,
                height: JSON.parse(result[i].mapLocation)[0].height,
                url: dictValue57[b].icon,
                bizId: result[i].indoorId,
                name: result[i].name,
                id: result[i].id,
                type: result[i].type,
                relationId: result[i].relationId,
                relationType: result[i].relationType,
                orgId: result[i].orgId,
                assetsIds: result[i].assetsIds,
              };
              coords.push(coord);
            }
          }
        }
      }
      addImageMarker(28, coords); //初始化打点
    }
  );
};

//显示标注点
var addImageMarker = function (size, coords, level) {
  for (var i = 0; i < coords.length; i++) {
    var groupLayer = map.getFMGroup(coords[i].bizId); //获取当前楼层
    if (groupLayer) {
      firstLayer = groupLayer.getOrCreateLayer("imageMarker");
      var im = new fengmap.FMImageMarker({
        x: coords[i].x,
        y: coords[i].y,
        z: coords[i].z,
        name: coords[i].name,
        height: 2.5,
        url: coords[i].url,
        id:
          coords[i].id +
          "@" +
          coords[i].type +
          "@" +
          coords[i].relationId +
          "@" +
          coords[i].relationType +
          "@" +
          coords[i].orgId +
          "@" +
          coords[i].assetsIds,
        size: size,
        callback: function () {
          im.alwaysShow();
        },
      });
      firstLayer.addMarker(im);
    }
  }

  //中心点
  var pnt = {
    x: coords[0].x,
    y: coords[0].y,
    groupID: coords[0].bizId, //目标层GroupID
    callback: function () {
      //跳转中心点完成
    },
  };
  //跳转
  map.moveTo(pnt);

  map.getFMGroup(coords[0].bizId).show = true;

  // 地图显示级别
  map.mapScaleLevel = {
    // 设置显示级别
    level: 20,
  };
};

//显示一个
var addOneMarker = function (coords) {
  if (coords) {
    var location = JSON.parse(coords.mapLocation);
    var groupLayer = map.getFMGroup(coords.indoorId ? coords.indoorId : 1); //获取当前楼层
    firstLayer = groupLayer.getOrCreateLayer("imageMarker");
    var im = new fengmap.FMImageMarker({
      x: location[0].x,
      y: location[0].y,
      z: location[0].z,
      name: "",
      height: 2.5,
      url: coords.mapIcon,
      size: 28,
      callback: function () {
        im.alwaysShow();
      },
    });
    firstLayer.addMarker(im);
  }
};
